local skel = fk.CreateSkill {
  name = "lb__lianjin",
  max_branches_use_time = function(self, player)
    local list = {}
    local names = Fk:getAllCardNames("t", true)
    for _, name in ipairs(names) do
      list[name] = { [Player.HistoryTurn] = 1 }
    end
    return list
  end
}

Fk:loadTranslationTable {
  ["lb__lianjin"] = "炼金",
  --[":lb__lianjin"] = "游戏开始时，你摸一张牌并将一张牌置为「<b>哲</b>」。每回合每种牌名限一次，你可以将一张与「<b>哲</b>」花色相同的手牌当目标至多为X（X为「<b>哲</b>」的数量）的任意普通锦囊牌使用，若于你回合内使用，你弃置一张此花色的「<b>哲</b>」。",
  --10.19
  [":lb__lianjin"] = "游戏开始时，你横置一名角色，摸两张牌并将至多两张牌置为「<b>哲</b>」。每回合每种牌名限一次，你可以将一张与「<b>哲</b>」花色相同的手牌当目标至多为X（X为「<b>哲</b>」的数量）的任意普通锦囊牌使用，若于你回合内使用，你弃置一张此花色的「<b>哲</b>」。",

  ["@@lb__lianjin-turn"] = "炼金同颜色「<b>哲</b>」",
  ["@[skill_cardname]lb__lianjin"] = "炼金",

  ["#lb__lianjin"] = "炼金：你可以将一张与「<b>哲</b>」花色相同的手牌当目标至多为 %arg 的普通锦囊牌使用",
  ["#lb__lianjin_ex"] = "炼金：你可以将一张与「<b>哲</b>」颜色相同的手牌当目标至多为 %arg 的普通锦囊牌使用",
  ["#lb__lianjin_dis"] = "炼金：请弃置一张%arg「<b>哲</b>」",
  ["#lb__lianjin_choose"] = "炼金：请将至多两张牌加入「<b>哲</b>」",
  ["#lb__lianjin_chained"] = "炼金：请横置一名角色",


  ["$lb__lianjin1"] = "魔术技巧！",
  ["$lb__lianjin2"] = "依此神技，萃精于糙。",
}

skel:addEffect("viewas", {
  pattern = ".|.|.|.|.|normal_trick|.",
  prompt = function(self, player, selected_cards, selected)
    if player:getMark("@@lb__lianjin-turn") > 0 then
      return "#lb__lianjin_ex:::" .. #player:getPile("lb__zhe_nakexia")
    end
    return "#lb__lianjin:::" .. #player:getPile("lb__zhe_nakexia")
  end,
  interaction = function(self, player)
    local all_choices = Fk:getAllCardNames("t", true)
    local choices = player:getViewAsCardNames(skel.name, all_choices)
    choices = table.filter(choices, function(name)
      return skel:withinBranchTimesLimit(player, name)
    end)
    if #choices > 0 then
      return UI.CardNameBox { choices = choices, all_choices = all_choices }
    end
  end,
  filter_pattern = {
    min_num = 1,
    max_num = 1,
    pattern = ".",
  },
  card_filter = function(self, player, to_select, selected, selected_targets)
    local card = Fk:getCardById(to_select)
    if #selected == 0 and self.interaction.data and table.contains(player:getCardIds("h"), to_select)
        and card.name ~= self.interaction.data
        and #player:getPile("lb__zhe_nakexia") > 0 then
      local suits, color = {}, {}
      for _, id in ipairs(player:getPile("lb__zhe_nakexia")) do
        table.insertIfNeed(suits, Fk:getCardById(id).suit)
        table.insertIfNeed(color, Fk:getCardById(id).color)
      end
      if player:getMark("@@lb__lianjin-turn") > 0 then
        return table.contains(color, card.color)
      end
      return table.contains(suits, card.suit)
    end
    return false
  end,
  target_filter = function(self, player, to_select, selected, selected_cards, card, extra_data)
    if #selected_cards ~= 1 or self.interaction.data == nil or #player:getPile("lb__zhe_nakexia") == 0 then return end
    local clone = Fk:cloneCard(self.interaction.data)
    clone.skillName = skel.name
    clone:addSubcards(selected_cards)
    return not clone.is_passive and #selected < #player:getPile("lb__zhe_nakexia") and player:canUseTo(clone, to_select) and
        clone.skill:modTargetFilter(player, to_select, selected, clone)
  end,
  feasible = function(self, player, selected, selected_cards, card)
    if #selected_cards ~= 1 or self.interaction.data == nil or #player:getPile("lb__zhe_nakexia") == 0 then return end
    local clone = Fk:cloneCard(self.interaction.data)
    clone.skillName = skel.name
    clone:addSubcards(selected_cards)
    if clone.is_passive then
      return player:canUseOrResponseInCurrent(clone)
    else
      return #selected <= #player:getPile("lb__zhe_nakexia") and #selected > 0
    end
  end,
  view_as = function(self, player, cards)
    return nil
  end,
  on_use = function(self, room, skillUseEvent, card, params)
    if self.interaction.data == nil then return end
    local player = skillUseEvent.from
    local tos = skillUseEvent.tos
    room:sortByAction(tos)
    local clone = Fk:cloneCard(self.interaction.data)
    clone.skillName = skel.name
    clone:addSubcards(skillUseEvent.cards)
    player:addSkillBranchUseHistory(skel.name, self.interaction.data)
    ---[[
    local skip = player:getMark("@@lb__lianjin-turn") > 0
    if skip then
      room:setPlayerMark(player, "@@lb__lianjin-turn", 0)
    end
    --]]
    --if not skip and player.phase ~= Player.NotActive then
    if player.phase ~= Player.NotActive then
      local ids = table.filter(player:getPile("lb__zhe_nakexia"), function(id)
        return skip and Fk:getCardById(id).color == clone.color or Fk:getCardById(id).suit == clone.suit
        --return Fk:getCardById(id).suit == clone.suit
      end)
      if #ids > 0 then
        if #ids > 1 then
          ids = room:askToCards(player, {
            min_num = 1,
            max_num = 1,
            skill_name = skel.name,
            pattern = tostring(Exppattern { id = ids }),
            expand_pile = ids,
            prompt = "#lb__lianjin_dis:::" .. (skip and clone:getColorString() or clone:getSuitString(true)),
            --prompt = "#lb__lianjin_dis:::" .. clone:getSuitString(true),
            cancelable = false,
          })
        end
        room:moveCardTo(ids, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, skel.name, skel.name, true, player)
      end
    end
    return { ---@type UseCardDataSpec
      from = player,
      tos = tos,
      card = clone,
      --extra_data = { lb__lianjin = clone:getSuitString(true) },
    }
  end,
  enabled_at_play = function(self, player)
    return #player:getPile("lb__zhe_nakexia") > 0
  end,
  enabled_at_response = function(self, player, response)
    return not response and #player:getPile("lb__zhe_nakexia") > 0
  end,
})

skel:addEffect(fk.GameStart, {
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(skel.name)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player:isAlive() then
      local tos = table.filter(room.alive_players, function(to)
        return not to.chained
      end)
      if #tos > 0 then
        if #tos > 1 then
          tos = room:askToChoosePlayers(player, {
            targets = tos,
            min_num = 1,
            max_num = 1,
            skill_name = skel.name,
            cancelable = false,
            prompt = "#lb__lianjin_chained",
          })
        end
        tos[1]:setChainState(true)
      end
    end
    if player.dead then return end
    player:drawCards(2, skel.name)
    if player.dead or player:isNude() then return end
    local ids = room:askToCards(player, {
      min_num = 1,
      max_num = 2,
      skill_name = skel.name,
      include_equip = true,
      cancelable = true,
      prompt = "#lb__lianjin_choose",
    })
    if #ids > 0 then
      player:addToPile("lb__zhe_nakexia", ids, true, skel.name, player)
    end
  end,
})

skel:addAcquireEffect(function(self, player, is_start)
  player.room:setPlayerMark(player, "@[skill_cardname]lb__lianjin",
    { name = skel.name, scope = Player.HistoryTurn, all_names = Fk:getAllCardNames("t", true) })
end)

skel:addLoseEffect(function(self, player, is_death)
  player.room:setPlayerMark(player, "@[skill_cardname]lb__lianjin", 0)
end)

return skel
